package com.example.li893.drag;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Vibrator;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;

public class DragView extends GridView {
    private Vibrator mVibrator;  //振动器
    private WindowManager mWindowManager;
    private WindowManager.LayoutParams mWindowLayoutParams; //镜像的参数设置

    private boolean isDrag = false;
    private int mDownX;
    private int mDownY; //定位拖拽的物体,按下的点到DragView的边缘的距离
    private int moveX;
    private int moveY;
    private View mDraggingItem = null; //拖拽的物体
    private ImageView mDragImageView; //用于拖拽的镜像
    private Bitmap mDragBitmap; //设置拖拽物体的bitmap

    private int mDownItemTop;
    private int mDownItemLeft;  //按下的点到该item的边缘的距离
    private int mDragViewTop;
    private int mDragViewLeft;  //DragView到屏幕边缘的距离

    private int mStatusHeight;

    private int mDragPosition; //正在拖拽的位置
    private int mDownScrollBorder;
    private int mUpScrollBorder;
    private static final int speed = 20; //DragView自动滚动的速度

    private long dragResponseMS = 1000;   //设置长按响应时间
    private Handler mHandler = new Handler(); //handler传递机制

    private OnDeleteListener onDeleteListener;
    private OnChangeListener onChangeListener; //设置回调的接口

    private int markFrom;
    private int markTo;

    public DragView(Context context) {
        this(context, null);
    }

    public DragView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DragView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mVibrator = (Vibrator)context.getSystemService(context.VIBRATOR_SERVICE);
        mWindowManager=(WindowManager)context.getSystemService(context.WINDOW_SERVICE);
        mStatusHeight = getStatusHeight(context);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch(ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mDownX = (int) ev.getX();
                mDownY = (int) ev.getY();
                mDragPosition = pointToPosition(mDownX, mDownY);
                if (mDragPosition == AdapterView.INVALID_POSITION) {   //对无效位置的判断
                    return super.dispatchTouchEvent(ev);
                }
                mHandler.postDelayed(mLongClickRunnable, dragResponseMS);
                mDraggingItem = getChildAt(mDragPosition - getFirstVisiblePosition());
                mDownItemTop = mDownY - mDraggingItem.getTop();
                mDownItemLeft = mDownX - mDraggingItem.getLeft();
                mDragViewTop = (int) (ev.getRawY() - mDownY);
                mDragViewLeft = (int) (ev.getRawX() - mDownX);
                mDownScrollBorder = getHeight() / 4;
                mUpScrollBorder = getHeight() * 3 / 4;
                mDraggingItem.setDrawingCacheEnabled(true); //开启mDraggingVItem绘图缓存
                mDragBitmap = Bitmap.createBitmap(mDraggingItem.getDrawingCache()); //获取mDraggingItem在缓存中的Bitmap对象
                mDraggingItem.destroyDrawingCache(); //释放绘图缓存，避免镜像重复
                break;
            case MotionEvent.ACTION_MOVE:
                int moveX = (int) ev.getX();
                int moveY = (int) ev.getY();
                if (isOverItem(mDraggingItem, moveX, moveY)) {   //不超过边Item边界就不移除长按
                    mHandler.removeCallbacks(mLongClickRunnable);
                }
                break;
            case MotionEvent.ACTION_UP:
                mHandler.removeCallbacks(mLongClickRunnable);
                mHandler.removeCallbacks(mScrollRunnable);
                break;
        }
        return super.dispatchTouchEvent(ev); //回调
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if(isDrag&&mDraggingItem!=null){
            switch(ev.getAction()){
                case MotionEvent.ACTION_MOVE:
                    moveX=(int)ev.getX();
                    moveY=(int)ev.getY();
                    onDragItem(moveX,moveY);
                    break;
                    case MotionEvent.ACTION_UP:
                        int X=(int)ev.getRawX();
                        int Y=(int)ev.getRawY();
                        onStopDrag(X,Y);
                        isDrag=false;
                        break;
            }
            return true;
        }
        return super.onTouchEvent(ev);
    }

    public void setDragResponseMS(long dragResponseMS) {
        this.dragResponseMS = dragResponseMS;
    }

    private Runnable mLongClickRunnable = new Runnable() {
        @Override
        public void run() {
            isDrag = true;
            mVibrator.vibrate(50);
            mDraggingItem.setVisibility(View.INVISIBLE);
            createDragImage(mDragBitmap,mDownX,mDownY);     //隐藏item,传入bitmap并显示镜像

        }
    };

    private void createDragImage(Bitmap bitmap, int downX, int downY) {
        mWindowLayoutParams = new WindowManager.LayoutParams();
        mWindowLayoutParams.format=PixelFormat.TRANSLUCENT;
        mWindowLayoutParams.gravity=Gravity.TOP|Gravity.LEFT;
        mWindowLayoutParams.x=downX-mDownItemLeft+mDragViewLeft;
        mWindowLayoutParams.y=downY-mDownItemTop+mDragViewTop-mStatusHeight;
        mWindowLayoutParams.alpha=0.55f;
        mWindowLayoutParams.width=WindowManager.LayoutParams.WRAP_CONTENT;
        mWindowLayoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT; //包裹自身内容
        mWindowLayoutParams.flags=WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;  //让该window不接受发送按键事件及按钮事件，触摸屏事件;
        mDragImageView=new ImageView(getContext());
        mDragImageView.setImageBitmap(bitmap);
        mWindowManager.addView(mDragImageView,mWindowLayoutParams);
    }

    private static int getStatusHeight(Context context){     //测量状态栏高度
        int statusHeight=0;
        Rect localRect = new Rect();
        ((Activity) context).getWindow().getDecorView().getWindowVisibleDisplayFrame(localRect);
        if (0 == statusHeight){
            Class<?> localClass;
            try {
                localClass = Class.forName("com.android.internal.R$dimen");
                Object localObject = localClass.newInstance();
                int i5 = Integer.parseInt(localClass.getField("status_bar_height").get(localObject).toString());
                statusHeight = context.getResources().getDimensionPixelSize(i5);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return statusHeight;
    }

    private boolean isOverItem(View Item,int x,int y){
        if(Item == null){
            return true;
        }

        if (x < Item.getLeft() || x > Item.getLeft() + Item.getWidth()) {
            return true;
        }
        if (y < Item.getTop() || y > Item.getTop() + Item.getHeight()) {
            return true;
        }
        return false;
    }

    private Runnable mScrollRunnable = new Runnable() {
        @Override
        public void run() {
            int scrollY;
            if(moveY>mUpScrollBorder){
                scrollY=speed;
                mHandler.postDelayed(mScrollRunnable,25);
            }else if(moveY<mDownScrollBorder){
                scrollY=-speed;
                mHandler.postDelayed(mScrollRunnable,25);
            }else{
                scrollY=0;
                mHandler.removeCallbacks(mScrollRunnable);
            }
            onSwapItem(moveX,moveY);
            smoothScrollBy(scrollY,10);
        }
    };

    private void onSwapItem(int moveX,int moveY){
        int temp=pointToPosition(moveX,moveY);
        if(temp!=mDragPosition&&temp!=AdapterView.INVALID_POSITION){
            if(onChangeListener!=null){
                markFrom=mDragPosition;
                markTo=temp;
                onChangeListener.onChange(mDragPosition,temp);
            }
            getChildAt(temp - getFirstVisiblePosition()).setVisibility(View.INVISIBLE);//拖动到了新的item,新的item隐藏掉
            getChildAt(mDragPosition - getFirstVisiblePosition()).setVisibility(View.VISIBLE);//之前的item显示出来
            mDragPosition = temp;
        }
    }

    private void onDragItem(int moveX,int moveY){
        mWindowLayoutParams.x = moveX - mDownItemLeft + mDragViewLeft;
        mWindowLayoutParams.y = moveY - mDownItemTop + mDragViewTop - mStatusHeight;
        mWindowManager.updateViewLayout(mDragImageView, mWindowLayoutParams);
        onSwapItem(moveX, moveY);				//GridView自动滚动
        mHandler.post(mScrollRunnable);
    }

    private void onStopDrag(int X,int Y){
        View view = getChildAt(mDragPosition - getFirstVisiblePosition());
        if(view != null){
                view.setVisibility(View.VISIBLE);
                if(Y<=mDragViewTop){
                onDeleteListener.onDelete(markFrom,markTo);
            }
        }
        removeDragImage();
    }

    private void removeDragImage(){
        if(mDragImageView != null){
            mWindowManager.removeView(mDragImageView);
            mDragImageView = null;
        }
    }

    public void setOnDeleteListener(OnDeleteListener onDeleteListener){
        this.onDeleteListener=onDeleteListener ;
    }

    public interface OnDeleteListener{
        void onDelete(int from,int to);
    }

    public void setOnChangeListener(OnChangeListener onChangeListener) {
        this.onChangeListener = onChangeListener;
    }

    public interface OnChangeListener{
        void onChange(int from, int to);
    }
}

